package com.sunlands.deskmate.message.handler.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.sunlands.deskmate.message.entity.Messages;
import com.sunlands.deskmate.service.impl.MongoMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import static com.sunlands.deskmate.config.RabbitMqConfig.QUEUE_MESSAGE_PERSIST;


/**
 * @author guoyang
 * @author liude
 */

@Component
@Slf4j
public class MessageListener extends AbstractInboundMessageWorker {

    private static final ScheduledThreadPoolExecutor EXECUTOR_ANSWER_SYSTEM = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(10);

    @Autowired
    private MongoMessageService messageService;

    @Autowired
    private ObjectMapper objectMapper;

    @RabbitListener(queues = QUEUE_MESSAGE_PERSIST + "_" + "${spring.profiles.active}")
    public void receiveContractQueue(Message mqMessage, Channel channel) throws IOException {
        try {
            if (mqMessage == null) {
                log.info("收到信息mqMessage为空！");
                return;
            }
            log.info("接收到的信息：{}", JSON.toJSONString(mqMessage));
            String message = new String(mqMessage.getBody());
            Messages msgEntity = JSONObject.parseObject(message, Messages.class);
            msgEntity.setId(null);
            messageService.insert(msgEntity);
        } catch (Exception e) {
            log.error("", e);
        } finally {
            handle(true, mqMessage, channel);
        }

    }


}
